const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());

// 缓存最近3个搜索
const searchCache = [];
const MAX_CACHE_SIZE = 3;

// 微服务端点配置
const SERVICES = {
    PYTHON: 'http://python-service:5000',
    JAVA: 'http://java-service:8080',
    CPP: 'http://cpp-service:8081',
    GO: 'http://go-service:8082'
};

// 搜索路由
app.get('/search', (req, res) => {
    const query = req.query.q;
    
    // 更新缓存
    searchCache.push(query);
    if(searchCache.length > MAX_CACHE_SIZE) searchCache.shift();
    
    // 调用Java二分搜索
    axios.get(`${SERVICES.JAVA}/search`, {
        params: {
            arr: [2, 5, 8, 12, 16].join(','),
            target: parseInt(query)
        }
    }).then(javaResp => {
        res.json({
            query,
            cache: searchCache,
            searchResult: javaResp.data
        });
    });
});

// 数据处理路由
app.post('/process', async (req, res) => {
    const { text, numbers } = req.body;
    
    try {
        // 并发调用多个服务
        const [reverseResp, matrixResp, duplicateResp] = await Promise.all([
            axios.post(`${SERVICES.PYTHON}/reverse`, { text }),
            axios.get(`${SERVICES.PYTHON}/matrix`),
            axios.post(`${SERVICES.CPP}/find-dups`, { data: numbers })
        ]);
        
        res.json({
            reversedText: reverseResp.data.result,
            matrix: matrixResp.data.result,
            duplicates: duplicateResp.data
        });
    } catch (error) {
        res.status(500).json({ error: "Service unavailable" });
    }
});

// 栈操作路由
app.route('/stack')
    .post(async (req, res) => {
        await axios.post(`${SERVICES.GO}/push`, { num: req.body.num });
        res.json({ status: "Pushed" });
    })
    .get(async (req, res) => {
        const response = await axios.get(`${SERVICES.GO}/pop`);
        res.json(response.data);
    });

app.listen(3000, () => console.log('Gateway running on port 3000'));